import NetUtils from '../utils/NetUtils.js'
import EmptyUtils from '../utils/EmptyUtils.js'
import Api from '../config/Api.js'

export default class LoginLogic {

  static login(callback) {

    let userInfoSource = wx.getStorageSync('userInfo')

    if (userInfoSource) {
      console.log('有数据')
      let leftTime = userInfoSource.lifeTime
      let currentTime = Date.parse(new Date()) / 1000

      if (currentTime < leftTime) {
        console.log('没过期')
      } else {
        console.log('过期了')
        wx.setStorageSync('userInfo', null)
        that.globalData.userInfo = null
      }
      return
    }


    // 登录
    wx.login({
      success: function (res) {
        let code = res.code;

        wx.getUserInfo({
          success: function (userInfoSource) {

            let userInfo = userInfoSource.userInfo
            let nickname = userInfo.nickName
            let avatar = userInfo.avatarUrl
            let sex = userInfo.gender         // 0 未知 1男 2女
            LoginLogic.getOpenId(code, nickname, avatar, sex, callback)
          }
        })
      }
    })
  }

  static getOpenId(code, nickname, avatar, sex, callback) {

    if (EmptyUtils.isE(code)) return

    let data = { code: code }

    NetUtils.R(Api.wechat_openid,
      data,
      function (res) {
        let openID = res.openId
        let loginData = {
          platform: 3,
          openId: openID,
          nickname: nickname,
          avatar: avatar,
          sex: sex
        }

        LoginLogic.weChatLogin(loginData, callback)
      },
      function (errRes) {
      },
      NetUtils.GET
    )
  }

  static weChatLogin(data, callback) {
    NetUtils.R(Api.wechat_login,
      data,
      (res) => {
        wx.setStorageSync('userInfo', res)
        callback(res)

      }, (errRes) => {
      },
      NetUtils.POST
    )

  }
}